package com.axx.android.letter.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.home.model.User;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.axx.android.utils.ImageUtils;
import com.google.gson.reflect.TypeToken;
import com.previewlibrary.PhotoActivity;
import com.previewlibrary.ThumbViewInfo;
import com.sendtion.xrichtext.DataImageView;
import com.sendtion.xrichtext.RichTextEditor;

import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class LetterWriterActivity extends BaseActivity {


    @Bind(R.id.btn_next)
    Button btnNext;
    @Bind(R.id.tv_location)
    TextView tvLocation;
    @Bind(R.id.tv_distance)
    TextView tvDistance;
    @Bind(R.id.tv_receiver)
    TextView tvReceiver;
    @Bind(R.id.et_title)
    EditText etTitle;
    @Bind(R.id.et_content)
    RichTextEditor etContent;
    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.tv_send)
    TextView tvSend;
    @Bind(R.id.tv_send_image)
    Button mTvSendImage;
    @Bind(R.id.root)
    LinearLayout root;
    @Bind(R.id.rb_start)
    RatingBar rbStart;
    @Bind(R.id.layout_header)
    LinearLayout mLayoutHeader;
    @Bind(R.id.layout_open)
    LinearLayout mLayoutOpen;
    @Bind(R.id.view_open)
    View mViewOpen;
    private User.UserListBean model;
    private File mAudioDir;
    final ArrayList<ThumbViewInfo> thumbViewInfos = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_writer_letter;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        model = (User.UserListBean) getIntent().getSerializableExtra("model");

        String fromCity = LetterApp.curLocation.getCity();
        tvLocation.setText(fromCity + "至" + model.getCityName());

        tvReceiver.setText("收件人：" + model.getNickName());
        tvSend.setText("发件人：" + LetterApp.authUser.getNickName());
        tvDistance.setText("距离：" + model.getDistance() + "km");

        etContent.setImageClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DataImageView imageView = (DataImageView) view;
                String image = imageView.getAbsolutePath();
                int postion = 0;
                for (int i = 0; i < thumbViewInfos.size(); i++) {
                    if (image.equals(thumbViewInfos.get(i).getUrl())){
                        postion = i;
                    }
                }
                PhotoActivity.startActivity(LetterWriterActivity.this,thumbViewInfos,postion);

            }
        });
    }


    @OnClick(R.id.btn_next)
    public void onViewClicked() {
        if (TextUtils.isEmpty(etTitle.getText().toString())) {
            showToast("请输入标题");
            return;
        }

        if (etTitle.getText().toString().length() < 4) {
            showToast("请输入标题，不小于4个字");
            return;
        }
        if (etTitle.getText().toString().length() > 15) {
            showToast("请输入标题，不大于15个字");
            return;
        }
        if (getContentLength() < 100) {
            showToast("请输入信件详情，不少于100个字");
            return;
        }
        if (getContentLength() > 2000) {
            showToast("请输入信件详情，不大于2000个字");
            return;
        }


        Intent intent = new Intent(this, LetterToolActivity.class);
        intent.putExtra("location", tvLocation.getText().toString());
        intent.putExtra("distance", tvDistance.getText().toString());
        intent.putExtra("model", model);
        intent.putExtra("title", etTitle.getText().toString());
        intent.putExtra("content", getEditData());
        intent.putExtra("star", rbStart.getRating() + "");
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_send_image)
    public void chooseImage() {
        MultiImageSelector.create(this)
                .single()
                .start(LetterWriterActivity.this, 100);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                String imagePath = path.get(0);
                if (imagePath != null) {
                    showLoading("上传照片中");
                    uploadImage(imagePath);
                } else {
                    showToast("选图失败，请重新选择");
                }
            }
        }
    }

    private void uploadImage(String imagePath) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("type", "2");
        hashMap.put("token", LetterApp.authUser.getToken());

        HttpUtils.postFile(ImageUtils.DEFAULT_IMAGE_SIZE,Constants.Url.Uploader.UPLOAD_IMAGE, "file", new File(imagePath), hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    BaseModel<String> baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<String>>() {
                    });
                    if (baseModel.isSuccess()) {
                        ThumbViewInfo thumbViewInfo = new ThumbViewInfo(baseModel.data);
                        thumbViewInfos.add(thumbViewInfo);
                        etContent.insertImage(baseModel.data, etContent.getMeasuredWidth());
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showErrorNet();
            }
        });
    }

    private int getContentLength() {
        List<RichTextEditor.EditData> editList = etContent.buildEditData();
        StringBuffer content = new StringBuffer();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
            }
        }
        return content.toString().length();
    }

    private String getEditData() {
        List<RichTextEditor.EditData> editList = etContent.buildEditData();
        StringBuffer content = new StringBuffer();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
            } else if (itemData.imagePath != null) {
                content.append("<img src=\"").append(itemData.imagePath).append("\"/>");
            }
        }
        return content.toString();
    }


    @OnClick(R.id.layout_open)
    public void layoutoOpen() {
        if (mLayoutHeader.getVisibility() == View.GONE) {
            mLayoutHeader.setVisibility(View.VISIBLE);
            mViewOpen.setBackgroundResource(R.drawable.ic_letter_open);
        } else {
            mLayoutHeader.setVisibility(View.GONE);
            mViewOpen.setBackgroundResource(R.drawable.ic_letter_close);
        }
    }
}
